import axios, {AxiosRequestConfig, AxiosResponse} from 'axios';
import {getCookie, removeCookie} from "./cookies";
import {message} from "./utils";

// export interface configType extends AxiosRequestConfig {
//     // url?: string,
//     // method?: string,
//     isToken?: boolean
// }

//把部分变成必选
type ToParietalDes<T extends AxiosRequestConfig, U extends keyof T> = Pick<T, Exclude<keyof T, U>> & Pick<T, U>;

interface resConfig extends AxiosResponse {
    code?: number,
    message?: string,
    records?: any[]
}

const noFreshApi = [
    '/auth/verifiCode/code',
    '/auth/oauth/token',
    '/oauth/token',
]
const service = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    method: 'POST',
    timeout: 20000,
    headers: {}
})

// // 记录错误日志
const errorLog = (err: Error) => {
    // 打印到控制台
    if (process.env.NODE_ENV === 'development') {
        console.log('>>>>>> Error >>>>>>')
        console.log(err)
    }
    // 显示提示
    message({
        message: err.message,
        type: 'error'
    })
}

// 请求拦截
service.interceptors.request.use(
    (config: ToParietalDes<AxiosRequestConfig, 'url'>) => {
        const isToken = noFreshApi.includes(config.url || '')
        if (!isToken) {
            const token = getCookie('mic-token')
            //非空断言
            config.headers!.Authorization = 'Bearer ' + token
        }
        // if (noFreshApi.includes(config.url))
        // const {isToken} = config
        // const rTime = cookies.get('refreshTime')
        // const rToken = cookies.get('refreshToken')
        // const loginTime = cookies.get('loginTime')
        // const nowTime = +new Date()
        // if (!noFreshApi[config.url] && !store.getters.isRefreshToken && rToken && nowTime - loginTime + 180000 > rTime * 1000) { // -180000 提前三分钟刷新token, 防止用户在使用期间token过期
        //     store.commit('user/set_isRefreshToken', true)
        //     refreshToken(rToken).then(res => {
        //         const { data } = res
        //         cookies.set('mic-token', data.token)
        //         cookies.set('refreshToken', data.refreshToken)
        //         cookies.set('refreshTime', data.expiresIn)
        //         cookies.set('loginTime', +new Date())
        //         store.commit('user/set_isRefreshToken', false)
        //     })
        // }
        // const token = cookies.get('mic-token')
        // if (token && token !== 'undefined') {
        // config.headers['Authorization'] = 'Bearer ' + token
        // }
        // if (config.data && !config.headers['Content-Type']) {
        // config.headers['Content-Type'] = 'application/json'
        // }
        // config.method = 'POST'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截
service.interceptors.response.use(
    (response: resConfig) => {
        const res = response.data
        if (res.code !== 200) {
            message({
                message: res.message,
                type: 'error',
                duration: 5
            })
            if (res.code === 401) {
                removeCookie('mic-token')
                window.location.replace('')
                //         // 清除权限缓存
                //         router.clearPermission()
                //         setTimeout(() => {
                //             router.push('/login')
                //         }, 1000)
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.log(error)
        if (error.response && error.response.code === 401) {
            // router.clearPermission()
        } else if (error.response && error.response.code === 500) {
            console.log(error)
            errorLog(new Error(`系统错误!: ${error.config.url}`))
        } else if (error.message && error.message.indexOf('timeout') > -1) {
            errorLog(new Error(`网络超时!: ${error.config.url}`))
        } else if (error.type === '403') {
            errorLog(new Error(`没有请求权限!: ${error.config.url}`))
        } else {
            errorLog(new Error(`网络错误!: ${error.config.url}`))
        }
        return Promise.reject(error)
    }
)

export default service
